import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/17 8:06
 * @description
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] words = {"a", "banana", "app", "appl", "ap", "apply", "apple"};
        solution.longestWord(words);
    }
    public String longestWord(String[] words) {
        Arrays.sort(words, (a, b)-> {
            if (a.length() == b.length()) {
                // 字母数相同按字典序降序排列
                return b.compareTo(a);
            }else {
                return a.length() - b.length();
            }
        });
        String longest = "";
        Set<String> set = new HashSet<>();
        set.add("");
        int n = words.length;
        for (String word : words) {
            if (set.contains(word.substring(0, word.length() - 1))) {
                set.add(word);
                longest = word;
            }
        }
        return longest;
    }
}
